package com.book.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadServlet() {
		super();

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		long sizeMax= 30 * 1024 * 1024;// 设置上传文件最大为 30M
		response.setCharacterEncoding("utf-8");
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
		diskFileItemFactory.setSizeThreshold(4096);//设置缓冲区大小
		diskFileItemFactory.setRepository(new File(request.getRealPath("/")+"upload"));//设置上传目录
	    ServletFileUpload servletFileUpload=	new ServletFileUpload(diskFileItemFactory);
	    servletFileUpload.setSizeMax(sizeMax);
	    PrintWriter out=response.getWriter();
	    @SuppressWarnings("rawtypes")
		List fileList=null;
	    try {
		fileList=	servletFileUpload.parseRequest(request);
			
			
		} catch (FileUploadException e) {
			
			if (e instanceof SizeLimitExceededException) {
				out.write("文件尺寸超过规定大小:" + sizeMax + "字节<p />");
				return;
			}
			e.printStackTrace();
		}
		if (fileList==null||fileList.size()==0) {
			out.println("请选择上传文件<p />");
			return;
		}
	 
	   Iterator iterator=	fileList.iterator();
	   while (iterator.hasNext()) {
		 
		String path=null;
		   long size=0;
		FileItem fileItem=null;
	    fileItem=	(FileItem) iterator.next();
	    if (fileItem.isFormField()||fileItem==null) {
			continue;
		}
	   path= fileItem.getName();
	   size = fileItem.getSize();
		if ("".equals(path) || size == 0) {
			out.println("请选择上传文件<p />");
			
			return;
		}
		String filename=path.substring(path.lastIndexOf("\\")+1);
		// 得到文件的扩展名(无扩展名时将得到全名)
		String t_ext = filename.substring(filename.lastIndexOf(".") + 1);
		
		long now = System.currentTimeMillis();
		// 根据系统时间生成上传后保存的文件名
		String prefix = String.valueOf(now);
		// 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下
		String u_name = request.getRealPath("/") + "upload/"
				+ prefix + "." + t_ext;
		try {
			fileItem.write(new File(u_name));
			out.println("文件上传成功. 已保存为: " + prefix + "." + t_ext
					+ " &nbsp;&nbsp;文件大小: " + size + "字节<p />");
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	    
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);

	}

}
